package com.aptech.forms.tdkhoa;

import com.aptech.beans.Users;
import com.aptech.dao.UserManager;
import com.aptech.utility.DBType;
import com.aptech.utility.DBUtil;
import com.aptech.validate.CryptoUtils;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.ImageIcon;

public class Login extends javax.swing.JFrame {

    public Login() {
        initComponents();
        // set windows center sreen
        setLocationRelativeTo(null);
        // set default button to be pressed is Submit
        getRootPane().setDefaultButton(jbtLoginSubmit);
//        checkConnection();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jtfLoginUsername = new javax.swing.JTextField();
        jbtLoginSubmit = new javax.swing.JButton();
        jbtLoginCancel = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jpwLoginPassword = new javax.swing.JPasswordField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Welcome");
        setIconImage(new ImageIcon(getClass().getResource("/com/image/icon.png")).getImage());
        setName("frameLogin"); // NOI18N
        setResizable(false);

        jLabel1.setFont(new java.awt.Font("Segoe UI Light", 1, 24)); // NOI18N
        jLabel1.setForeground(new java.awt.Color(0, 102, 255));
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/image/004.png"))); // NOI18N
        jLabel1.setText("Login");
        jLabel1.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);

        jtfLoginUsername.setFont(new java.awt.Font("Segoe UI Light", 1, 14)); // NOI18N
        jtfLoginUsername.setForeground(new java.awt.Color(255, 0, 51));
        jtfLoginUsername.setToolTipText("Typical your account");
        jtfLoginUsername.setPreferredSize(new java.awt.Dimension(60, 20));

        jbtLoginSubmit.setFont(new java.awt.Font("Segoe UI Light", 1, 14)); // NOI18N
        jbtLoginSubmit.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/image/003.png"))); // NOI18N
        jbtLoginSubmit.setMnemonic('S');
        jbtLoginSubmit.setText("Submit");
        jbtLoginSubmit.setToolTipText("Click here to login");
        jbtLoginSubmit.setSelected(true);
        jbtLoginSubmit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtLoginSubmitActionPerformed(evt);
            }
        });

        jbtLoginCancel.setFont(new java.awt.Font("Segoe UI Light", 1, 14)); // NOI18N
        jbtLoginCancel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/image/005.png"))); // NOI18N
        jbtLoginCancel.setMnemonic('C');
        jbtLoginCancel.setText("Cancel");
        jbtLoginCancel.setToolTipText("Click here to exit program");
        jbtLoginCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtLoginCancelActionPerformed(evt);
            }
        });

        jLabel2.setFont(new java.awt.Font("Segoe UI Light", 1, 14)); // NOI18N
        jLabel2.setForeground(new java.awt.Color(255, 0, 0));
        jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/image/001.png"))); // NOI18N
        jLabel2.setText("Username:");

        jLabel3.setFont(new java.awt.Font("Segoe UI Light", 1, 14)); // NOI18N
        jLabel3.setForeground(new java.awt.Color(255, 0, 0));
        jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/image/002.png"))); // NOI18N
        jLabel3.setText("Password:");

        jpwLoginPassword.setFont(new java.awt.Font("Segoe UI Light", 1, 14)); // NOI18N
        jpwLoginPassword.setToolTipText("Typical your password");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap(43, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel3))
                        .addGap(26, 26, 26)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jpwLoginPassword, javax.swing.GroupLayout.DEFAULT_SIZE, 212, Short.MAX_VALUE)
                            .addComponent(jtfLoginUsername, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(61, 61, 61)
                        .addComponent(jbtLoginSubmit)
                        .addGap(27, 27, 27)
                        .addComponent(jbtLoginCancel, javax.swing.GroupLayout.PREFERRED_SIZE, 119, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 379, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(36, 36, 36)
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 170, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(29, 29, 29)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jtfLoginUsername, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(25, 25, 25)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jpwLoginPassword, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jbtLoginSubmit, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jbtLoginCancel, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(45, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jbtLoginCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtLoginCancelActionPerformed
        this.dispose();
    }//GEN-LAST:event_jbtLoginCancelActionPerformed

    private void jbtLoginSubmitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtLoginSubmitActionPerformed
        try {
//            if (checkConnection()) {

                // Encrypt password to md5
                MessageDigest messageDigest = MessageDigest.getInstance("MD5");
                messageDigest.reset();

                String password = String.valueOf(jpwLoginPassword.getPassword());
                messageDigest.update(password.getBytes(),
                        0, jpwLoginPassword.getPassword().length);

                // password after encryption md5
                String md5 = new BigInteger(1, messageDigest.digest()).toString(16);

                Users bean = UserManager.getRow(jtfLoginUsername.getText(), md5);

                if (bean == null) {
                    JOptionPane.showMessageDialog(this, "Login failed!", "Message", JOptionPane.ERROR_MESSAGE);
                } else {
                    JOptionPane.showMessageDialog(this, "Login sucessfully!", "Message", JOptionPane.INFORMATION_MESSAGE);

                    // Save user infor to properties file and ecryption
                    {

                        // Create file and directory
//                    Path newDirectoryPath = Paths.get(System.getenv("APPDATA") + File.separator + "Aptech");
//                    Path keyFilePath = Paths.get(System.getenv("APPDATA") + File.separator + "Aptech" + File.separator + "msbdata.key");
//                    Path pwdFilePath = Paths.get(System.getenv("APPDATA") + File.separator + "Aptech" + File.separator + "msbdata.properties");
//                    if (!Files.exists(newDirectoryPath)) {
//                        Files.createDirectory(newDirectoryPath);
//                        if (!Files.exists(keyFilePath) && !Files.exists(pwdFilePath)) {
//                            try {
//                                Files.createFile(keyFilePath);
//                                Files.createFile(pwdFilePath);
//                            } catch (IOException e) {
//                                System.err.println(e);
//                            }
//                        }
//                    }
                        final String KEY_FILE = "E:/howto.key";
                        final String PWD_FILE = "E:/howto.properties";

                        String clearPwd = String.valueOf(jpwLoginPassword.getPassword());

                        Properties p1 = new Properties();
                        File keyFile = new File(KEY_FILE);
                        FileWriter fw = new FileWriter(new File(PWD_FILE));

                        p1.put("UserName", jtfLoginUsername.getText().trim());
                        //String encryptedPwd = CryptoUtils.encrypt(clearPwd, new File(KEY_FILE));
                        p1.put("Password", CryptoUtils.encrypt(clearPwd, keyFile));
                        p1.store(fw, "");

                        fw.flush();
                        fw.close();
                    }

                    new Main().setVisible(true);
                    this.dispose();
                }
//            }

        } catch (NoSuchAlgorithmException ex) {
            System.err.println(ex.getMessage());
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, "Connection failed\nTry again", "Connection error", JOptionPane.ERROR_MESSAGE);
        } catch (GeneralSecurityException ex) {
            Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
        }

//        if (jtfLoginUsername.getText().equals("admin") && String.valueOf(jpwLoginPassword.getPassword()).equals("admin"))
//        {
//            JOptionPane.showMessageDialog(this, "Login sucessfully!", "Message", JOptionPane.INFORMATION_MESSAGE);
//            new Main().setVisible(true);
//            this.dispose();
//        }
    }//GEN-LAST:event_jbtLoginSubmitActionPerformed

    private static void sleepThread() {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException ex) {
            // Do something, if there is a exception
            System.out.println(ex.toString());
        }
    }

    public static void main(String args[]) {
        //sleepThread();
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
        } catch (UnsupportedLookAndFeelException ex) {
            Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
        }//System.err.println(ex.getMessage());
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {

                new Login().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JButton jbtLoginCancel;
    private javax.swing.JButton jbtLoginSubmit;
    private javax.swing.JPasswordField jpwLoginPassword;
    private javax.swing.JTextField jtfLoginUsername;
    // End of variables declaration//GEN-END:variables

//    private boolean checkConnection() {
//        Connection conn = null;
//        try {
//            // if connection is null
//            // call setting properties network
//            conn = DBUtil.getConnection(DBType.myConnection);
//        } catch (SQLException ex) {
//            JOptionPane.showMessageDialog(null, "Cannot connect to server", "Connection error", JOptionPane.ERROR_MESSAGE);
//            new CheckConnection().setVisible(true);
//        }
//        return conn != null;
//    }
}
